﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading;
using KaiXin.BLL;
using KaiXin.DTO.Tycoon;
using KaiXin.BLL.Tycoon;
using KaiXin.DAL.XML;
using KaiXin.BLL.Interface;

namespace TycoonWindowsService
{
    partial class Tycoon : ServiceBase
    {
        private Thread priceThead;
        private bool flag = true;


        public Tycoon()
        {
            InitializeComponent();
        }
        
        protected override void OnStart(string[] args)
        {
            priceThead = new Thread(RefreshPrice);
            priceThead.Start();
            
        }

        protected override void OnStop()
        {
            flag = false;
            for (int i = 0; i < 10 && priceThead.IsAlive; i++)
            {
                Thread.Sleep(1000);
            }


            if (priceThead.IsAlive)
            {
                priceThead.Abort();
            }
        }

        /// <summary>
        /// 刷新价格(供windows服务刷新价格使用)
        /// </summary>
        public void RefreshPrice()
        {
            IKXTycoon kx = new KXTycoon();
            kx.PriceChangeEvent += new PriceChange(Commission.Action);//价格变动时候的委托
            while (flag)
            {
                try
                {
                    Thread.Sleep(1000 * 30);//半分钟刷一次
                    kx.GetGoods();
                }
                catch (Exception ex)
                {
                    Log.WriteLog(ex.Message + "[" + DateTime.Now + "]", "c:\\KaiXinException.txt");
                }

            }
        }
    }
}
